package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.*;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.javassist.compiler.ast.Variable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R<IPage> findAll(Integer page, Integer pageSize, String name) {

        IPage<Dish> pa = new Page<>(page, pageSize);
        //创建dishdtos的查询 此时没有值
        IPage<DishDto> dishDtosPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);

        dishService.page(pa, lambdaQueryWrapper);

        List<Dish> records = pa.getRecords();
        List<DishDto> dishDtosList = new ArrayList<>();
        for (Dish dish : records) {
            DishDto dishDtos = new DishDto();

            //每一个dish中的对象 存入到dishdtos中
            BeanUtils.copyProperties(dish, dishDtos);
            //获取分类id;
            Long categoryId = dish.getCategoryId();
            //根据id查询分类名称并设置dishdtos
            dishDtos.setCategoryName(categoryService.getById(categoryId).getName());

            //将得到的分类名称存入list集合中 此时dishdtos中存了dish中的数据+分类名称
            dishDtosList.add(dishDtos);

        }
        //将disdtos集合放入page<dishdto>中作为分页查询数据
        dishDtosPage.setRecords(dishDtosList);
        dishDtosPage.setTotal(pa.getTotal());

        // dishService.page(pa, lambdaQueryWrapper);
        return R.success(dishDtosPage);

    }

    @PostMapping
    public R add(@RequestBody DishDto dishDto) {

        dishService.saveDish(dishDto);

        redisTemplate.delete("dish_" + dishDto.getCategoryId());

        return R.success("添加成功");
    }

    //根据id回显数据
    @GetMapping("/{id}")
    public R selectById(@PathVariable Long id) {
        //根据传过来的id查询数据
        Dish byId = dishService.getById(id);
        //创建dto对象
        DishDto dishDto = new DishDto();
        //将byid这组数据放入dto中
        BeanUtils.copyProperties(byId, dishDto);
        //根据id查询口味是否存在
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId, id);
        //根据条件查询口味
        List<DishFlavor> flavors = dishFlavorService.list(lambdaQueryWrapper);

        //将数据存入dto
        dishDto.setFlavors(flavors);

        return R.success(dishDto);

    }

    @PutMapping
    public R updateById(@RequestBody DishDto dishDto) {
        //将修改的数据存入dish表
        dishService.updateById(dishDto);
        //获取当前修改数据的id用于修改dishflavors表
        Long id = dishDto.getId();

        //根据id查询口味表，修改口味比较特殊 可能会删除，可能会添加 ，所会可以根据id将原表中的口味全部删除
        //然后从前端传来的数据直接做添加动作
        //1.条件查询
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId, id);
        //将查询到的数据全部删除   delete form dishflavors where id = #{id}
        dishFlavorService.remove(lambdaQueryWrapper);
        //将前端获取到的更改口味直接添加
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
            dishFlavorService.save(flavor);
        }

        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success(" 修改成功");
    }

    @Transactional
    @DeleteMapping
    public R<String> delete(@RequestParam List<String> ids) {
        //获取所有要删除的id
        for (String id : ids) {
            //根据id直接删除
            dishService.removeById(id);
            //根据id查询dishflavors表中口味并删除
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, id);
            dishFlavorService.remove(lambdaQueryWrapper);

        }


        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    public R<String> updateBystatus(Long[] ids, @PathVariable Integer status) {
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            dishService.updateById(dish);

        }

        return R.success("操作成功");
    }

    @GetMapping("/list")
    //categoryid
    public R<List<DishDto>> list(Dish dish) {
        //先查询redis中是否已经存在如果存在直接查询，如果没有先查询数据库，在将数据存入redis
        String dishRedisId = "dish_" + dish.getCategoryId();
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(dishRedisId);
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dish::getCategoryId, dish.getCategoryId()).eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(lambdaQueryWrapper);
        //创建dishdto集合 将每个dish数据存入集合中数据
        dishDtoList = new ArrayList<>();
        for (Dish dishList : list) {
            //创建dto对象 用来拷贝
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dishList, dishDto);
            //获取dish表中categoryId
            Long categoryId = dish.getCategoryId();
            //添加分类名称setCategoryName
            dishDto.setCategoryName(categoryService.getById(categoryId).getName());
            //获取当前菜品id
            Long id = dishList.getId();
            //查询口味表中dish_id 与id相同的口味数据
            LambdaQueryWrapper<DishFlavor> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.eq(DishFlavor::getDishId, id);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            dishDtoList.add(dishDto);
        }
        redisTemplate.opsForValue().set(dishRedisId, dishDtoList);

        return R.success(dishDtoList);

    }

}
